package com.bingxue.edu.framework.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.bingxue.edu.framework.common.model.Response;
import com.bingxue.edu.framework.common.util.HttpContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

/**
 * 全局异常处理器
 * @author panbo
 * @since 2024/6/28
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 拦截校验异常-方法参数无效异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<Void> handleException(MethodArgumentNotValidException exception) {
        String errorMsg = CollUtil.join(exception.getAllErrors(), StrUtil.COMMA, DefaultMessageSourceResolvable::getDefaultMessage);
        return response(new BusinessException(CommonErrorCode.PARAM_INVALID, errorMsg));
    }

    /**
     * 拦截请求路径未匹配到的异常
     */
    @ExceptionHandler(NoResourceFoundException.class)
    public Response<Void> handleException(NoResourceFoundException exception) {
        return response(new NotFoundException(exception.getMessage()));
    }

    @ExceptionHandler(NotLoginException.class)
    public Response<Void> handleException(NotLoginException exception) {
        return response(new AuthException(exception.getMessage()));
    }

    @ExceptionHandler(NotPermissionException.class)
    public Response<Void> handleException(NotPermissionException exception) {
        return response(new BusinessException(CommonErrorCode.REQUEST_UNAUTHORIZED));
    }

    @ExceptionHandler(ErrorCodeException.class)
    public Response<Void> handleException(ErrorCodeException exception) {
        return response(exception);
    }

    @ExceptionHandler(Exception.class)
    public Response<Void> handleException(Exception exception) {
        return response(new SystemException(exception));
    }

    /**
     * 响应ErrorCodeException异常
     */
    private Response<Void> response(ErrorCodeException exception) {
        if (exception.isSystemError()) {
            log.error("请求[{}]出错, [{}] {}", HttpContextHolder.getRequestUri(), exception.getErrorCode(), exception.getMessage(), exception);
        } else {
            log.warn("请求[{}]失败, [{}] {} ", HttpContextHolder.getRequestUri(), exception.getErrorCode(), exception.getMessage());
        }
        HttpContextHolder.getResponse().setStatus(exception.getStatusCode());
        return Response.fail(exception.getErrorCode(), exception.getErrorMessage());
    }
}
